<?php
/*
 * ---------------------------------------------------------------
* Author  : Anthony Tran
* Email   : Incredibletran@gmail.com - Incredibletran@hotmail.com
* Version : 1.2
* ---------------------------------------------------------------
*/
include APPPATH.'controllers/admin_controller'.EXT;
class Gallery extends Admin_controller{
	function __construct(){
		parent::__construct();
		$this->load->model(array('gallery_model'));
		$this->load->library(array('session','upload'));
		$this->load->helper(array('link','upload','text'));
		ini_set("memory_limit","120M");
		ini_set("time_execution", 3600);
		
		$user_account = $this->session->userdata('user');
		if($user_account['group'] != "admin" && $user_account['group'] != "editor") redirect(admin_url());	// Check if user is not administrator role then can not add new account
		
		if($this->session->userdata('language')){
			$language   =   $this->session->userdata('language');
		}else{
			$language  =   '';
		}
		
		if ($language == LANG) {
			$this->lang->load(LANG, LANG_FOLDER);
		}else{
			$this->lang->load(LANG_DEFAULT, LANG_FOLDER_DEFAULT);
		}
	}
	
	
	function index(){

		#get data.
		$gallery_list					=	$this->gallery_model->get_list();
		$gallery_url					=	$this->selfURL();
		$this->session->set_userdata('gallery_url', $gallery_url);
		
		$gallery_category				=	$this->gallery_model->get_cate();
		

		$data['gallery_category']	=	$gallery_category;
		$data['current_url']		=	$gallery_url;
		$data['gallery_list']		=	$gallery_list;
		$data['select']				=	"gallery";
		$data['tpl_file']			=	"gallery";
		$this->load->view('admin/layout/index', $data);
	}
	
	
	function get_album(){
		$album_id = $this->input->post('album_id'); 
		$all_photos	=	$this->gallery_model->get_photos_in_album($album_id);
		if(count($all_photos[0])>0){
			foreach ($all_photos as $key => $image){
				echo "<li class='albumImage'>";
	            	echo "<div class='picHolder'>";
	                	echo "<span class='image_highlight'></span>";
	                    echo "<a href='".base_url().$image->image_url."' rel='glr'></a>";	
	                    echo "<img src='".base_url().$image->thumb_url."' title='Drag Image to delete' style='width:160px; height:120px;' />";
			            echo "<div class='picTitle'>".$image->name."</div>";
			            echo "<ul class='dataImg'>"; 
			            	echo "<li>".$image->id."</li>";
			                echo "<li>".$image->name."</li>";
			            echo "</ul>";  
	                echo "</div>";
	            echo "</li>";
			}
		}
	}
	
	
	function add_image($album_id){
		if($_SERVER['REQUEST_METHOD'] == "POST"){
			$this->form_validation->set_message('required', $this->lang->line('form_required'));
			$this->form_validation->set_rules('title', $this->lang->line('title'), 'required|trim|xss_clean');
			if($this->form_validation->run() == true){
				$cate_info	=	$this->gallery_model->get_album_info($album_id);
				$info		=	array();
				$gallery	=	array();
				$album_dir 	= 	'uploads/gallery/'.date('Y-m-d').'/'.$cate_info['name_ascii'].'/';
				$thumb_dir	=	'uploads/gallery/'.date('Y-m-d').'/'.$cate_info['name_ascii'].'/thumbs/';
				
					$flag = true;
					if($_FILES["images_0"]["name"] == ""){
						$data['error'] = $this->lang->line('image_required');
					}else {
						for($i=0; $i<count($_FILES); $i++){
							if($_FILES["images_$i"]["name"] != ""){
								$ext = get_ext($_FILES["images_$i"]["name"]);
								if(!in_array($ext, array('png', 'gif', 'jpg', 'jpeg'))) {
									$data['error'] = $this->lang->line('format_required');
									$flag = false;
								}elseif($_FILES["images_$i"]["size"] > 2*1024*1024){
									$data['error'] = $this->lang->line('size_required');
									$flag = false;
								}
							}else{
								$data['error']	=	"Please input all fieds required above!";
							}
						}
						// Make directory 
						if(isset($flag) && $flag != false){
							if(!is_dir($album_dir)) create_dir($album_dir);
							if(!is_dir($thumb_dir)) create_dir($thumb_dir);
						}
						for($i=0; $i<count($_FILES); $i++){
							if(isset($flag) && $flag != false){
								
									#upload.
									$config['upload_path']			= 	$album_dir;
									$config['allowed_types']		= 	'jpg|png|jpeg|gif';
									$config['file_name']			=	ascii_link($_FILES["images_$i"]["name"]);
									$config['max_size']				= 	'2048';
				
									$this->load->library('upload', $config);
									$this->upload->initialize($config);
									$image							= 	$this->upload->do_upload("images_$i");
									$image_data[$i] 				= 	$this->upload->data();
									if($image) {
										#upload execute.
										$info[$i]['image_url']		=	$config['upload_path'].$image_data[$i]['file_name'];
										$info[$i]['title']			=	$this->input->post('title');
										$info[$i]['title_ascii']	=	ascii_link($this->input->post('title'));
										$info[$i]['cate_id']		=	$this->input->post('category');
										$info[$i]['date_created']	=	date('Y-m-d');
										$info[$i]['name']			=	$image_data[$i]['file_name'];
										$err1						=	true;
									} else {
										$data['error'] = $this->upload->display_errors();
										$err1 = false;
									}
								
							}//End if($flag1 $flag2)
						}//End for image

						if(isset($err1) && $err1 == true){
							for($i=0;$i<count($image_data);$i++){
								#create thumb.
								$config['image_library'] 	= 	'gd2';
								$config['source_image']		= 	$image_data[$i]['full_path'];
								$config['new_image']		=	$thumb_dir;
								$config['maintain_ratio'] 	= 	TRUE;
								$config['width']	 		= 	160;
								$config['height']			= 	120;
					
								$this->load->library('image_lib');
								$this->image_lib->initialize($config);
					
								$thumb 						= 	$this->image_lib->resize();
								$info[$i]['thumb_url']		=	$config['new_image'].$image_data[$i]['orig_name'];
								$err2						=	true;
								if(! $thumb){
									$data['error'] = $this->image_lib->display_errors();
									$err2 = false;
								}
								$this->image_lib->clear();
							}//End for thumb
						}	
						#Pop info into array
						if(isset($err2) && $err2 == true){
							foreach ($info as $k => $v){
								$gallery[$k]	=	$v;
								#insert into database
								$this->gallery_model->add($gallery[$k]);
							}
							$data['success'] = 'Add photos successfully !';
						}
					}//End else($_FILES["images_0"])
							
			}else{
				$data['error'] = "Can not add new photo to this album";
			}// End if(form_validation)
		}
		$album_info			=	$this->gallery_model->get_album_info($album_id);
		
		$data['cate']		=	$this->gallery_model->get_cate();
		$data['albumid']	=	$album_id;
		$data['album_info']	=	$album_info;
		$data['tpl_file']	=	"add";
		$data['select']		=	"gallery";
		$this->load->view('admin/layout/index', $data);
	}
	
	
	function edit_gallery(){
		$albumid			=	$this->input->post('id_edit');
		$info['name']		=	$this->input->post('name');
		$info['name_ascii']	=	ascii_link($this->input->post('name'));
		
		$this->gallery_model->edit($albumid, $info);
		$this->session->set_userdata('edit-success', 'yes');
		$url		=	$this->session->userdata('gallery_url');
		redirect($url, 'refresh');
	}
	
	
	
	/* function add(){
		if($_SERVER['REQUEST_METHOD'] == "POST"){
			#set rules
			$this->form_validation->set_message('required', $this->lang->line('form_required'));
			$this->form_validation->set_rules('title', $this->lang->line('title'), 'required|trim|xss_clean');
			if($this->form_validation->run() == TRUE){
				#create gallery album
				$info		=	array();
				$gallery	=	array();
				$album_dir 	= 	'uploads/gallery/';
				$thumb_dir	=	'uploads/gallery/thumbs/';
				if(!is_dir($album_dir)){
					create_dir($album_dir);
				}
				if(!is_dir($thumb_dir)){
					create_dir($thumb_dir);
				}
				
				#check title exist or not
				if($this->gallery_model->check_exist($this->input->post('title'))) {
					die($this->lang->line('title_exist'));
				}else{
					if($_FILES["images_0"]["name"] == ""){
						die($this->lang->line('image_required'));
					}else {
						for($i=0; $i<count($_FILES); $i++){
							if($_FILES["images_$i"]['name'] != ""){
								$ext = get_ext($_FILES["images_$i"]["name"]);
								if(!in_array($ext, array('png', 'gif', 'jpg', 'jpeg'))) {
									die($this->lang->line('format_required'));
								}elseif ($_FILES["images_$i"]["size"] > 2*1024*1024){
									die($this->lang->line('size_required'));
								}else {
									#upload.
									$config['upload_path']			= 	$album_dir;
									$config['allowed_types']		= 	'jpg|png|jpeg|gif';
									$config['file_name']			=	ascii_link($_FILES["images_$i"]["name"]);
									$config['max_size']				= 	'2048';
						
									$this->load->library('upload', $config);
									$this->upload->initialize($config);
									$image							= 	$this->upload->do_upload("images_$i");
									$image_data[$i] 				= 	$this->upload->data();
									if($image) {
										#upload execute.
										$info[$i]['image_url']		=	$config['upload_path'].$image_data[$i]['file_name'];
										$info[$i]['title']			=	$this->input->post('title');
										$info[$i]['title_ascii']	=	ascii_link($this->input->post('title'));
										$info[$i]['cate_id']		=	$this->input->post('category');
										$info[$i]['date_created']	=	date('Y-m-d');
									} else {
										die($this->upload->display_errors());
									}
								}//End if(!in_array)
							}//End if($_FILES["images"]["name"])
						}//End for image
							
						for($i=0;$i<count($image_data);$i++){
							#create thumb.
							$config['image_library'] 	= 	'gd2';
							$config['source_image']		= 	$image_data[$i]['full_path'];
							$config['new_image']		=	$thumb_dir;
							$config['maintain_ratio'] 	= 	TRUE;
							$config['width']	 		= 	75;
							$config['height']			= 	50;
								
							$this->load->library('image_lib');
							$this->image_lib->initialize($config);
						
							$thumb 						= 	$this->image_lib->resize();
							$info[$i]['thumb_url']		=	$config['new_image'].$image_data[$i]['orig_name'];
						
							if(! $thumb){
								die($this->image_lib->display_errors());
							}
							$this->image_lib->clear();
						}//End for thumb
							
						#Pop info into array
						foreach ($info as $k => $v){
							$gallery[$k]	=	$v;
							#insert into database
							$this->gallery_model->add($gallery[$k]);
						}
						die('yes');
					}//End else($_FILES["images_0"])
					
				}//End if($this->gallery_model...)
			}else{
				die(validation_errors());
			}//End if(form_validation->run())
		}
		
		$data['cate']	=	$this->gallery_model->get_cate();
		$this->load->view('add', $data);
	} */
	
	
	
	
	function delete($albumid){
		#get album's photos 
		$photos			=	$this->gallery_model->get_photos_in_album($albumid);
		$albumDetail	=	$this->gallery_model->get_album_info($albumid);
		$album			=	$this->gallery_model->get_cate();
		$url			=	$this->session->userdata('gallery_url');
		if(count($album) <= 1 ){
			$this->session->set_userdata('no-empty', 'no');
			redirect($url);
		}
		
		#delete photos
		if(count($photos[0])>0){
			foreach ($photos as $photo){
				remove_dir($photo->image_url);
				remove_dir($photo->thumb_url);
				
				#delete information in DB.
				$this->gallery_model->delete($photo->id);
			}
			#remove album directory
			$date = $photos[0]->date_created;
			$albumdir	=	"uploads/gallery/".$date."/".$albumDetail['directory_name'];
			$dir		=	"uploads/gallery/".$date;
			//remove album's directory
			if(is_dir($albumdir)){
				remove_directory($albumdir);
			}
			//remove yyyy-mm-dd directory if it's empty
			if(is_dir($dir)){
				if(is_empty_dir($dir) == true){
					rmdir($dir);
				}
			}
		}
		
		#delete album
		$this->gallery_model->delete_album($albumid);
		
		$delete	=	"yes";
		$this->session->set_userdata('delete_gallery', $delete);
		 
		
		redirect($url,'refresh');
	}
	
	
	function delete_photo(){
		$photo_id 		= $this->input->post('photo_id');
		$photo_info		= $this->gallery_model->get_match($photo_id);
		$find_brothers 	= $this->gallery_model->get_brothers($photo_id, $photo_info->cate_id);
		
		if($find_brothers == true){
			//Delete photo
			remove_dir($photo_info->thumb_url);
			remove_dir($photo_info->image_url);
			$this->gallery_model->delete($photo_id);
			exit('yes');
		}else{
			exit('no');
		}
		
	}
	
	
	function selfURL(){
		if(!isset($_SERVER['REQUEST_URI'])){
			$serverrequri = $_SERVER['PHP_SELF'];
		}else{
			$serverrequri =    $_SERVER['REQUEST_URI'];
		}
		$protocol 	= strpos(strtolower($_SERVER['SERVER_PROTOCOL']),'https') === FALSE ? 'http' : 'https';
		$host     	= $_SERVER['HTTP_HOST'];
		$port 		= ($_SERVER["SERVER_PORT"] == "80") ? "" : (":".$_SERVER["SERVER_PORT"]);
	
	
		$currentUrl = $protocol . '://' . $host . $port .$_SERVER['REQUEST_URI'];
	
		return $currentUrl;
	}
	
	
	function multi_upload($configs,$files){
		$this->load->library('upload', $config);
		if(count($configs) != count($files)){
			return 'array_count_wrong';
		}
	
		$errors = $successes = array();
	
		for($i=0, $j = count($files);$i<$j;$i++){
			$this->upload->initialize($config[$i]);
		
			if( ! $this->upload->do_upload($files[$i])){
				$errors[$files[$i]] = $this->upload->display_errors();
			}else{
				$successes[$files[$i]] = $this->upload->data();
			}
		}
	
		return array($errors, $successes);
		}



}


/*---------------------------------------------End-----------------------------------------*/